﻿/**************************************************************************/
/*   Mapping provided by Boggle.                                          */
/*   Copyright of Boggle Ltd.                                             */
/*   The script is provided as part of a single organisation license, no  */
/*   part of the script may be copied or modified without express         */
/*   permission from the copyright holder.                                */
/*   All queries regarding this file can be directed to:                  */
/*   Hadley Pettigrew                                                     */
/*   hadley@boggle.co.nz                                                  */
/*                                                                        */
/**************************************************************************/

var divCount = 0;
var editingEntities = new Array();

function LoadData() {

    //Load the xml mapping data
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.open("GET", "/WebResources/boggle_EntityAddressMapping.xml", false);
    xmlhttp.send();
    var dataXmlDoc = xmlhttp.responseXML;

    var mappings = dataXmlDoc.getElementsByTagName("Entity");

    var mappingArray = new Array();

    if (mappings != null) {
        for (var i = 0; i < mappings.length; i++) {
            var mapping = new Object();
            var entityName = mappings[i].getAttribute("id");
            mapping.Type = entityName;

            var idElem = mappings[i].getElementsByTagName("Id");
            mapping.Id = idElem[0].childNodes[0].nodeValue;

            var nameElem = mappings[i].getElementsByTagName("Name");
            if (nameElem != null && nameElem.length == 1)
                mapping.Name = nameElem[0].childNodes[0].nodeValue;
            else
                mapping.Name = "";

            var streetElem = mappings[i].getElementsByTagName("Street");
            if (streetElem != null && streetElem.length == 1)
                mapping.Street = streetElem[0].childNodes[0].nodeValue;
            else
                mapping.Street = "";

            var cityElem = mappings[i].getElementsByTagName("City");
            if (cityElem != null && cityElem.length == 1)
                mapping.City = cityElem[0].childNodes[0].nodeValue;
            else
                mapping.City = "";

            var countryElem = mappings[i].getElementsByTagName("Country");
            if (countryElem != null && countryElem.length == 1)
                mapping.Country = countryElem[0].childNodes[0].nodeValue;
            else
                mapping.Country = "";

            var latitudeElem = mappings[i].getElementsByTagName("Latitude");
            if (latitudeElem != null && latitudeElem.length == 1)
                mapping.Latitude = latitudeElem[0].childNodes[0].nodeValue;
            else
                mapping.Latitude = "";

            var longitudeElem = mappings[i].getElementsByTagName("Longitude");
            if (longitudeElem != null && longitudeElem.length == 1)
                mapping.Longitude = longitudeElem[0].childNodes[0].nodeValue;
            else
                mapping.Longitude = "";

            mappingArray[i] = mapping;
        }
    }
    return mappingArray;
}

function DisplayEntities() {
    var mappingArray = LoadData();
    var mappingEditor = "";
    for (var i = 0; i < mappingArray.length; i++) {
        var mapping = mappingArray[i];
        mappingEditor += GetEntityInfoStr(mapping);
    }

    var editorDiv = document.getElementById("EntityEditor");

    editorDiv.innerHTML = mappingEditor;
}

function GetEntityInfoStr(mapping) {
    var returnStr = "";
    if (mapping != null) {
        var entityName = mapping.Type;
        if (entityName == null || entityName == "") {
            entityName = divCount;
        }
        //Store this entity as an entity being edited
        editingEntities[divCount] = entityName;
        //Create div header
        returnStr += "<div id='" + entityName + "'><input type='text' id='entity' class='title' value='" + entityName + "' /><a id='button" + entityName + "' href='javascript:Toggle(\"" + entityName + "\")'>Show</a>";
        //Create content div
        returnStr += "<div id='content" + entityName + "' class='hidden'>";
        //Add table element
        returnStr += "<table>";
        //Add id of entity
        returnStr += GetFieldStr("Id", "Identifier", mapping.Id);
        //Add name of entity (label)
        returnStr += GetFieldStr("Name", "Display Name", mapping.Name);
        //Add field for street
        returnStr += GetFieldStr("Street", "Street", mapping.Street);
        //Add field for City
        returnStr += GetFieldStr("City", "City", mapping.City);
        //Add field for Country
        returnStr += GetFieldStr("Country", "Country", mapping.Country);
        //Add field for Latitude
        returnStr += GetFieldStr("Latitude", "Latitude", mapping.Latitude);
        //Add field for Longitude
        returnStr += GetFieldStr("Longitude", "Longitude", mapping.Longitude);
        //Complete the table
        returnStr += "</table>";
        //Add the remove button
        returnStr += "<a class='button' href='javascript:RemoveEntity(\"" + entityName + "\")'>Remove</a>";
        //Add end div tag
        returnStr += "</div></div>";
        divCount++;
    }
    return returnStr;
}

function GetFieldStr(fieldname, friendlyname, value) {
    return "<tr><td class='fieldname'>" + friendlyname + ": </td><td class='value'><input id='" + fieldname + "' type='text' value='" + value + "' /></td></tr>";
}

function Toggle(entity) {
    //Get the div element
    var divElement = document.getElementById("content" + entity);
    var buttonElement = document.getElementById("button" + entity);

    if (divElement.className == "hidden") {
        divElement.className = "visible";
        buttonElement.Text = "Hide";
    }
    else {
        divElement.className = "hidden";
        buttonElement.Text = "Show";
    }
}

function addnewentity() {
    var mapping = new Object();
    mapping.Type = "";
    mapping.Id = "";
    mapping.Name = "";
    mapping.Street = "";
    mapping.City = "";
    mapping.Country = "";
    mapping.Latitude = "";
    mapping.Longitude = "";

    var editorDiv = document.getElementById("EntityEditor");

    editorDiv.innerHTML += GetEntityInfoStr(mapping);
}

function RemoveEntity(entity) {
    var ans = confirm("Are you sure you want to delete this entity mapping?");
    if (ans == true) {
        var entityDivElement = document.getElementById(entity);
        if (entityDivElement != null) {
            var editorDiv = document.getElementById("EntityEditor");

            editorDiv.removeChild(entityDivElement);
        }
    }
}

var ODataPath;
var serverUrl;

function init() {
    // Set Global Variables
    serverUrl = location.protocol + "//" + location.host;
    ODataPath = serverUrl + "/XRMServices/2011/OrganizationData.svc";
}

function save() {
    var okCancelRtn = confirm("Are you sure you want to Save?");
    if(okCancelRtn != true)
        return;

    //Get the xml
    var mappingXml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?><EntityAddressMappings>";
    for (var i = 0; i < editingEntities.length; i++) {
        mappingXml += GetEntityXml(editingEntities[i]);
    }

    //Get the data webresource id
    init();
    //https: //intergen13.crm5.dynamics.com/xrmservices/2011/organizationdata.svc

    var retrieveWebResourceReq = new XMLHttpRequest();
    retrieveWebResourceReq.open("GET", ODataPath + "/WebResourceSet?$filter=Name eq 'boggle_EntityAddressMapping.xml'&$select=WebResourceId", true);
    retrieveWebResourceReq.setRequestHeader("Accept", "application/json");
    retrieveWebResourceReq.setRequestHeader("Content-Type", "application/json; charset=utf-8");
    retrieveWebResourceReq.onreadystatechange = function () {
        retrieveWebResourceReqCallBack(this, mappingXml);
    };
    retrieveWebResourceReq.send();
}

function GetEntityXml(entityName) {
    var returnStr = "";
    var contentElement = document.getElementById("content" + entityName);
    if (contentElement != null) {
        //Get the typed in name
        //Find the title element
        var entityNameText = document.getElementById(entityName);
        var actEntityName = entityNameText.value;
        //Don't allow blank entities
        if (actEntityName != null && actEntityName != "") {
            returnStr += "<Entity id=\"" + actEntityName + "\">";

            //Get the id element
            var idElem = contentElement.getElementById("Id");
            var idVal = idElem.value;
            if (idVal == null)
                idVal = "";

            returnStr += "<Id>" + idVal + "</Id>";

            //Get the name element
            var nameElem = contentElement.getElementById("Name");
            var nameVal = nameElem.value;
            if (nameVal == null)
                nameVal = "";

            returnStr += "<Name>" + nameVal + "</Name>";

            //Get the street element
            var streetElem = contentElement.getElementById("Street");
            var streetVal = streetElem.value;
            if (streetVal == null)
                streetVal = "";

            returnStr += "<Address><Street>" + streetVal + "</Street>";

            //Get the city element
            var cityElem = contentElement.getElementById("City");
            var cityVal = cityElem.value;
            if (cityVal == null)
                cityVal = "";

            returnStr += "<City>" + cityVal + "</City>";

            //Get the country element
            var countryElem = contentElement.getElementById("Country");
            var countryVal = countryElem.value;
            if (countryVal == null)
                countryVal = "";

            returnStr += "<Country>" + countryVal + "</Country></Address>";

            //Get the latitude element
            var latitudeElem = contentElement.getElementById("Latitude");
            var latitudeVal = latitudeElem.value;
            if (latitudeVal == null)
                latitudeVal = "";

            returnStr += "<LatLong><Latitude>" + latitudeVal + "</Latitude>";

            //Get the longitude element
            var longitudeElem = contentElement.getElementById("Longitude");
            var longitudeVal = longitudeElem.value;
            if (longitudeVal == null)
                longitudeVal = "";

            returnStr += "<Longitude>" + longitudeVal + "</Longitude></LatLong>";

            //Finish the entity tag
            returnStr += "</Entity>";
        }
    }
    return returnStr;
}

function retrieveWebResourceReqCallBack(retrieveWebResourceReq, mappingXml) {
    if (retrieveWebResourceReq.readyState == 4 /* complete */) {
        if (retrieveWebResourceReq.status == 200) {
            //Success
            var retrievedWebResource = JSON.parse(retrieveWebResourceReq.responseText).d;

            //NEXT STEP: Update the Webresource
            updateWebResourceRecord(retrievedWebResource.results[0].WebResourceId, mappingXml);
        }
        else {
            //Failure
            errorHandler(retrieveAccountReq);
        }
    }
}

function updateWebResourceRecord(Id, mappingXml) {
    var updateWebResourceReq = new XMLHttpRequest();
    var changes = new Object();
    changes.Content = mappingXml;
    updateWebResourceReq.open("POST", ODataPath + "/WebResourceSet(guid'" + Id + "')", true);
    updateWebResourceReq.setRequestHeader("Accept", "application/json");
    updateWebResourceReq.setRequestHeader("Content-Type", "application/json; charset=utf-8");
    updateWebResourceReq.setRequestHeader("X-HTTP-Method", "MERGE");
    updateWebResourceReq.onreadystatechange = function () {
        updateWebResourceReqCallBack(this, Id);
    };
    updateWebResourceReq.send(JSON.stringify(changes));
}

function updateWebResourceReqCallBack(updateWebResourceReq, Id) {
    if (updateWebResourceReq.readyState == 4 /* complete */) {
        //There appears to be an issue where IE maps the 204 status to 1223 when no content is returned.
        if (updateWebResourceReq.status == 204 || updateWebResourceReq.status == 1223) {
            //Success
            showMessage("Saved XML Successfully.");
        }
        else {
            //Failure
            errorHandler(updateWebResourceReq);
        }
    }
}

//Function to display information on the HTML page.
function showMessage(message) {
    var dvMessage = document.createElement("div");
    dvMessage.innerHTML = message;
    document.getElementById("status").appendChild(dvMessage);
}


//Function to handle any http errors
function errorHandler(XmlHttpRequest) {
    showMessage("Error : " +
        XmlHttpRequest.status + ": " +
        XmlHttpRequest.statusText + ": " +
        JSON.parse(XmlHttpRequest.responseText).error.message.value);
}

function EncodeXml(xml) {
    return xml.replace(/\&/g, '&' + 'amp;').replace(/</g, '&' + 'lt;')
        .replace(/>/g, '&' + 'gt;').replace(/\'/g, '&' + 'apos;').replace(/\"/g, '&' + 'quot;');
}